/**在引擎源代码的基础上进行扩展*/
require("GTool")

var scheduleList = GTool.createMapObj(true);

var GOverload = {
    _test() {
        console.log(scheduleList);
    },

    /**扩展相关功能 */
    init() {
        this.editorExtend();
        this.functionExtend();
    },

    /**引擎源代码扩展函数  
     * 1.扩展button点击函数,添加通用点击音效  
     */
    functionExtend() {
        if (CC_EDITOR || !cc.director.getScheduler()) {
            return;
        }
        console.log("functionExtend");

        if (sa.IS_NATIVE()) {
            var __handler;
            if (window['__errorHandler']) {
                __handler = window['__errorHandler']
            }
            window['__errorHandler'] = function (...args) {
                console.error(JSON.stringify(arguments[3]).replace(/\\n/g, ""));
                var data = {
                    point: "__errorHandler",
                    stack: arguments[3],
                }
                sa.Request.reportError(data);
                if (__handler) {
                    __handler(...args)
                }
            }
        }

        /**覆盖button组件TouchBegan */
        var _oldTouchBegan = cc.Button.prototype._onTouchBegan;
        cc.Button.prototype._onTouchBegan = function (event) {
            var buttonName = this.node.name;
            if (buttonName.indexOf("item") < 0) {
                sa.Audio.playEffect("click1");
            }
            if (_oldTouchBegan) _oldTouchBegan.call(this, event);
        };

        /**覆盖Label组件onLoad */
        var _oldLabelOnLoad = cc.Label.prototype.onLoad;
        cc.Label.prototype.onLoad = function () {
            if (this.font instanceof cc.TTFFont) {
                sa.Font.setTTFFont(this);
            } else if (!this.font) {
                // if (this.lineHeight <= this.fontSize) {
                //     this.lineHeight = this.fontSize + 10;
                // }
                // this.useSystemFont = true;
                // this.fontFamily = "微软雅黑";
                sa.Font.setTTFFont(this);
            }
            if (_oldLabelOnLoad) _oldLabelOnLoad.call(this);
        };

        var oldSet = Object.getOwnPropertyDescriptor(cc.Sprite.prototype, "spriteFrame").set;
        Object.defineProperty(cc.Sprite.prototype, "spriteFrame", {
            set: function (value, force) {
                GEvent.dispatcher(GEventType.SPRITE_FRAME_CHANGED, "change", this.spriteFrame, value);
                oldSet.call(this, value, force);
            }
        });

        /**动作回调 */
        var oldexecute = cc.CallFunc.prototype.execute;
        cc.CallFunc.prototype.execute = function () {
            try {
                if (oldexecute) oldexecute.call(this);
            } catch (e) {
                console.error("execute", this.name, JSON.stringify(e.stack).replace(/\\n/g, ""));
                var data = {
                    point: "execute",
                    stack: e.stack,
                }
                sa.Request.reportError(data);
            }
        };

        /**定时器包装起来, 运行时定位问题 */
        var oldSchedule = cc.director.getScheduler().schedule;
        cc.director.getScheduler().schedule = function (callback, target, interval, repeat, delay, paused) {
            var fn = function () {
                if (this instanceof cc.Node) {
                    if (!cc.isValid(this)) {
                        if (!IS_DEBUG) {
                            GTimer.cancelAllTimer(this);
                        }
                        console.warn("schedule error, node is invalid");
                        return;
                    }
                }
                try {
                    callback.call(this);
                } catch (e) {
                    console.error("schedule", this._id, this.name, JSON.stringify(e.stack).replace(/\\n/g, ""));
                    var data = {
                        point: "schedule",
                        stack: e.stack,
                    }
                    sa.Request.reportError(data);
                }
            }
            scheduleList[target._id] = scheduleList[target._id] || [];
            var schedule = scheduleList[target._id];

            for (var i = 0; i < schedule.length; i++) {
                if (schedule[i].fn == callback || schedule[i].callback == callback) {
                    console.warn("重复定时器");
                    return;
                }
            }
            var _testFlag = "";
            if (target.name) _testFlag = target.name;
            if (target.node) _testFlag = target.node.name;
            schedule.push({ fn: fn, callback: callback, _testFlag: _testFlag });
            if (oldSchedule) oldSchedule.call(this, fn, target, interval, repeat, delay, paused);
        }

        var oldUnschedule = cc.director.getScheduler().unschedule;
        cc.director.getScheduler().unschedule = function (callback, target) {
            var schedule = scheduleList[target._id];
            if (!schedule) {
                // console.warn("停止不存在的定时器");
                return;
            }
            for (var i = schedule.length - 1; i >= 0; i--) {
                if (schedule[i].fn == callback || schedule[i].callback == callback) {
                    if (oldUnschedule) oldUnschedule.call(this, schedule[i].fn, target);
                    schedule.splice(i, 1);
                }
            }
            if (schedule.length == 0) {
                delete scheduleList[target._id];
            }
        }

    },

    /**cocos编辑器扩展函数  
     * 
     */
    editorExtend() {
        /**1.改变cc.Label的默认值  
         * 默认字体：微软雅黑  
         * 默认水平对齐方式：居中  
         * 默认竖直对齐方式：居中  
         * 默认排版方式：缩放  
         * 默认文字：“9999”  
         * 默认是否自动换行：否  
         */
        // if (CC_EDITOR) {
        //     // Editor.assetdb.queryAssets("db://assets/resources/font/ttf/**\/*", "ttf-font", (err, results) => {
        //     //     results.forEach(result => {
        //     //         if (result.url.endsWith("Lang_EN.TTF")) {
        //     //             Editor.log(result.uuid);
        //     //         }
        //     //     });
        //     // });

        //     cc.AssetLibrary.loadAsset("59f5d43c-a68b-43a8-b146-ea47ac0d5c07", function (err, asset) {
        //         if (!err) {
        //             cc.Class.Attr.getClassAttrs(cc.Label).__proto__._N$file$_$visible = true;
        //             cc.Class.Attr.getClassAttrs(cc.Label).__proto__._N$file$_$default = asset;
        //         }
        //     });
        // }
        // cc.Class.Attr.getClassAttrs(cc.Label).__proto__._isSystemFontUsed$_$default = false;

        this.change(cc.Label, "fontFamily", "default", "微软雅黑");
        this.change(cc.Label, "horizontalAlign", "default", 1);
        this.change(cc.Label, "verticalAlign", "default", 1);
        // this.change(cc.Label, "overflow", "default", 1);
        this.change2(cc.Label, "string", "default", "9999");
        this.change2(cc.Label, "enableWrapText", "default", false);

        /**
         * 2.改变cc.Button的默认值  
         * 默认过渡类型为：缩放动画
         */
        this.change(cc.Button, "transition", "default", 3);
        this.change3(cc.Button, "zoomScale", "default", 1.1);

        /**
         * 3.改变cc.Widget的默认值  
         * 默认对齐模式为：Once  
         * 默认底部对齐像素为：260
         */
        // this.change3(cc.Widget, "alignMode", "default", 1);
        // this.change2(cc.Widget, "bottom", "default", 260);
    },

    /**改变系统组件组件的默认值1 */
    change(component, key, type, value) {
        cc.Class.Attr.getClassAttrs(component).__proto__["_N$" + key + "$_$" + type] = value;
    },
    /**改变系统组件组件的默认值2 */
    change2(component, key, type, value) {
        cc.Class.Attr.getClassAttrs(component).__proto__["_" + key + "$_$" + type] = value;
    },
    /**改变系统组件组件的默认值3 */
    change3(component, key, type, value) {
        cc.Class.Attr.getClassAttrs(component).__proto__[key + "$_$" + type] = value;
    },
};

window.GOverload = GOverload;
GOverload.init();